<?php
namespace app\api\controller;

use app\admin\model\QuestionData as CommonDataModel;
use app\admin\model\QuestionFormat as CommonFormatModel;
use app\api\model\Wx;
use app\common\controller\Api;
use app\common\service\Question as QService;
use think\Db;

class Question extends Api
{
    protected $noNeedLogin = [
        'getQuestionList', 'submitQuestion', 'getQuestionInfo',
        'getCommentList', 'DoneQuestionnaire', 'getQuestionnaireDataDetail ',
    ];
    // protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $user_id     = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id ?? 0;
    }

    /**
     * @MethodName 问卷列表
     * @Author
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getQuestionList()
    {
        $model = Db::name('child_q_format');
        $list  = $model
            ->field('id as qid,q_class_id,name as title,is_automatic')
            ->where(['delete_time' => 0])
            ->where(['available' => 1])
            ->where(['uid' =>$this->user_id])
            ->order('qid desc')
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['my'] = db::name('child_q_data')->where('qid', $value['qid'])->where(['uid' => $this->user_id])->find();
        }

        $this->success('請求成功', $list);

    }

    /**
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-04T14:55:12+0800
     * @param      string
     * @return     [array]
     */
    public function getQuestionInfo()
    {
        $cat_id = $this->request->post("qid", 7);

        $where = [];
        if ($cat_id) {
            $where['id'] = $cat_id;
        }

        $model = Db::name('child_q_format');
        $info  = $model
            ->where($where)
            ->find();
        $this->success('請求成功', $info);
    }

    /**
     * 填写问卷模板
     * 1.检验参数
     * 2.判断是否自动打分
     * 3.处理（打分，保存） 填写 dealt字段
     * 4.问卷模板填写数+1  用户填写问卷数+1
     * 5.返回分数或者"填写成功，待后台人员处理"
     */
    public function DoneQuestionnaire()
    {
        $uid = $this->user_id;

        //判断是否传了参数
        $postData = input();
        // var_dump(5555,$postData);
        // die;
        if (! QService::checkDoneQuestionnaireParam($postData)) {
            return $this->error('问卷数据错误');
        }
        //找到对应模板
        $qid         = $postData['qid'];
        $center_id   = $postData['center_id'];
        $formatModel = CommonFormatModel::get($qid);
        if ($formatModel['available'] == 0) {
            return $this->error('该问卷模板尚未激活！');
        }
        $mark = null;
        $pass = null;
        $data = [
            'qid'          => $qid,
            'center_id'    => $center_id, //活动Id,2024-10-26
            'uid'          => $uid,
            'data'         => json_encode($postData['data']),
            'viewed'       => 1,
            'is_automatic' => $formatModel['is_automatic'],
        ];
        if ($formatModel['is_automatic'] == 1) {
            //打分
            $mark = QService::computeMark($formatModel, $postData['data']);
            if ($mark >= $formatModel['pass_mark']) {
                $pass  = 1;
                $dealt = 1;
            } else {
                $dealt = 0;
                $pass  = 0;
            }

        } else {
            $dealt = 0;
        }
        $data['mark']        = $mark;
        $data['dealt']       = $dealt;
        $data['pass']        = $pass;
        $data['create_time'] = date("Y-m-d H:i:s");

        $res = (new CommonDataModel)->insertGetId($data);
        $this->QuestionDataLog($res);

        $formatModel->setInc('count', 1);

        $this->success('請求成功', ['score' => $mark]);

    }

    public function QuestionDataLog($id)
    {
        $info = \think\Db::table('ftu_child_q_data')->where(['id' => $id])->find();
        if (empty($info)) {
            return;
        }
        $data = json_decode($info['data'], true);

        if (empty($data)) {
            return;
        }

        $insert_data = [];
        foreach ($data as $v) {

            //单选 和 跳题
            if ($v['type'] == 0 || $v['type'] == 6) {
                $row = [
                    'fid'  => $info['qid'],
                    'did'  => $info['id'],
                    'cid'  => $v['id'],
                    'type' => $v['type'],
                ];
                $row['choice']    = $v['choice'];
                $row['value']     = '';
                $row['other_str'] = $v['other_str'] ?? '';
                $insert_data[]    = $row;
            }
            //单选填空
            if ($v['type'] == 3) {
                $row = [
                    'fid'  => $info['qid'],
                    'did'  => $info['id'],
                    'cid'  => $v['id'],
                    'type' => $v['type'],
                ];
                $row['choice']    = 0;
                $row['value']     = $v['answer'];
                $row['other_str'] = '';
                $insert_data[]    = $row;
            }

            //多選題
            if ($v['type'] == 1) {
                foreach ($v['choice_list'] as $key => $val) {
                    $row = [
                        'fid'    => $info['qid'],
                        'did'    => $info['id'],
                        'cid'    => $v['id'],
                        'type'   => $v['type'],
                        'choice' => $key,
                        'value'  => $val,
                    ];

                    $row['other_str'] = $v['other_str'];
                    $insert_data[]    = $row;
                }

            }

            //填空题 矩阵题
            if ($v['type'] == 4 || $v['type'] == 2) {
                foreach ($v['answer_list'] as $key => $val) {
                    $row = [
                        'fid'       => $info['qid'],
                        'did'       => $info['id'],
                        'cid'       => $v['id'],
                        'type'      => $v['type'],
                        'choice'    => $key,
                        'value'     => $val,
                        'other_str' => '',
                    ];

                    $insert_data[] = $row;
                }

            }
        }

        \think\Db::table('ftu_child_data_log')->insertAll($insert_data);

    }

    /***
     * 获取问卷数据详情
     */
    public function getQuestionnaireDataDetail()
    {

        $id = input('param.')['id'];

        //找到问卷数据
        $data = QService::getQuestionnaireDataDetail($id);
        //判断是否是该用户填写的

        //获取题目数据
        $format = CommonFormatModel::get($data['qid']);
        //置为已看
        $data['data']     = json_decode($data['data'], true);
        $format['format'] = json_decode($format['format'], true);

        $this->success('請求成功', compact(['format', 'data']));

    }

    public function myQuestion()
    {
        if (empty($this->user_id)) {
            $this->success('請求成功', []);
        }
        $model = Db::name('child_q_data')->alias('a');
        $list  = $model
            ->join('child_q_format b', 'a.qid = b.id')
            ->field('a.id,a.dealt,a.mark,a.note,a.pass,a.viewed,a.qid,b.name as title')
            ->where(['a.delete_time' => 0])
            ->where(['a.uid' => $this->user_id])
            // ->where(['a.available'=>1])

            ->order('qid desc')
            ->select();

        $this->success('請求成功', $list);

    }

    //过滤非utf8 得字符串
    protected function getUtf8Str($str)
    {
        return preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]' .
            '|[\x00-\x7F][\x80-\xBF]+' .
            '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*' .
            '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})' .
            '|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
            '?', $str);
    }

    public function code()
    {
        $wx   = new Wx();
        $qid  = 16;
        $page = 'pages/fill/fills';
        $res  = $wx->getUnlimit($qid, $page, 'trial');
        var_dump($res);
    }

    public function add_user()
    {
        $params = input();
        $uid    = $this->user_id;
        $data   = [
            'name'      => $params['name'],
            'uid'       => $uid,
            'gender'    => $params['gender'],
            'birthday'  => $params['birthday'],
            'id_card'   => $params['id_card'],
            'phone'     => $params['nd_mobile'],
            'bind_uid'  => $params['select_id'],
            'bind_name' => $params['select_name'],
            'addtime'   => time(),
        ];

        try {
            Db::name('user_add')->insert($data);
        } catch (\Exception $e) {
            $this->error('操作失败', ['msg' => $e->getMessage()]);
        }
        $this->success('操作成功', []);

    }

    public function edit_user()
    {
        $params = input();
        if (! isset($params['id']) || empty($params['id'])) {
            $this->error('操作失败', ['msg' => '非法請求']);
        }
        $data = [
            'name'      => $params['name'],
            'gender'    => $params['gender'],
            'birthday'  => $params['birthday'],
            'id_card'   => $params['id_card'],
            'phone'     => $params['nd_mobile'],
            'bind_uid'  => $params['select_id'],
            'bind_name' => $params['select_name'],
        ];
        try {
            Db::name('user_add')->where(['id' => $params['id']])->update($data);
        } catch (\Exception $e) {
            $this->error('操作失败', ['msg' => $e->getMessage()]);
        }
        $this->success('操作成功', []);
    }

    public function list_user()
    {
        $uid   = $this->user_id;
        $model = Db::name('user_add');
        $list  = $model
            ->where(['uid' => $uid])
            ->order('id desc')
            ->select();

        $this->success('請求成功', $list);
    }

    public function del_user()
    {
        $params = input();
        if (! isset($params['id']) || empty($params['id'])) {
            $this->error('操作失败', ['msg' => '非法請求']);
        }

        try {
            // Db::name('user_add')->where(['id'=>$params['id']])->delete();
        } catch (\Exception $e) {
            $this->error('操作失败', ['msg' => $e->getMessage()]);
        }
        $this->success('操作成功', []);
    }

    public function system_list_user()
    {
        $uid   = $this->user_id;
        $model = Db::name('user_add');
        $list  = $model
            ->where(['uid' => $uid])
            // ->field('id,name')
            ->order('id desc')
            ->select();

        $this->success('請求成功', $list);
    }

}
